﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Activities.Domain.WorkflowInstances;
using Happy.Activities.Domain.Workflows.Internal;

namespace Happy.Activities.Domain.Workflows
{
    /// <summary>
    /// 代表了流程中的一个分流节点。
    /// </summary>
    public class SplitActivity : Activity
    {
        /// <inheritdoc />
        protected internal override ActivityInstance CreateInstance(WorkflowContext context, string routerSplitToken = SplitTokenHelper.DefaultSplitToken)
        {
            var activityInstanceId = Guid.NewGuid();

            return new ActivityInstance
            {
                Id = activityInstanceId,
                ActivityId = this.Id,
                SplitToken = SplitTokenHelper.CombineSplitToken(routerSplitToken, activityInstanceId),
                State = ActivityState.New,
                WorkflowInstanceId = context.WorkflowInstance.Id
            };
        }

        /// <inheritdoc />
        protected override bool CanEnter(WorkflowContext context, ActivityInstance activityInstance)
        {
            return true;
        }

        /// <inheritdoc />
        protected override void OnEnter(WorkflowContext context, ActivityInstance activityInstance)
        {
            this.Exit(context, activityInstance);
        }

        /// <inheritdoc />
        protected override bool CanExit(WorkflowContext context, ActivityInstance activityInstance)
        {
            return true;
        }

        /// <inheritdoc />
        protected override void OnExit(WorkflowContext context, ActivityInstance activityInstance)
        {
            var routers = context
                .WorkflowInstance
                .Workflow
                .GetRoutersByFromId(this.Id);

            foreach (var router in routers)
            {
                if (router.GetCondition().CanRoute(context, activityInstance, router))
                {
                    router.Route(context, activityInstance);
                }
            }
        }
    }
}
